import { MongoDb } from './src/utils/mongo';
import { Config } from './src/config';
import { configRouter } from './src/routers';
import { Router } from 'express';

const fs = require('fs');
const express = require('express');
const app = express();
const keeper = require('@moebius/http-graceful-shutdown').GracefulShutdownManager;

console.log('Reading config...');
const config = JSON.parse(fs.readFileSync('config.json')) as Config;

configRouter(config).then(routers => {
	configServer(routers);
});

function configServer(routers: Router) {
	console.log('Setting up server...');
	app.set('views', './views');
	app.set('view engine', 'pug');
	app.use('/', routers);

	let server = app.listen(config.port);
	console.log(`kb4409 listening on port ${config.port}`);

	let killer = new keeper(server);
	process.on('SIGTERM', () => {
		MongoDb.close();
		killer.terminate(() => {
			console.log('[SIGTERM] Server closed');
			process.exit();
		});
	});
	process.on('SIGINT', () => {
		MongoDb.close();
		killer.terminate(() => {
			console.log('[SIGINT] Server closed');
			process.exit();
		});
	});
}
